# -!- coding: utf-8 -!-
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
通过查找数据库中借款订单，然后根据还款日期查询需要还款的本金、利息、罚息、违约金
1.罚息=当期本金*0.001*逾期天数
2.违约金：当期已还-->剩余T期本金*0.03四舍五入后全部相加，利息为0，本金为剩余本金之和
         当期未还-->剩余T-1期本金*0.03四舍五入后全部相加，利息为当期利息，本金为剩余本金之和
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

import json
from datetime import datetime
from decimal import Decimal
from interfacetest.baseset.msydloan_api import API_MSYD
from pycacho.cachobase.deal_float import float_deal
#from msydwork.config.config_msydloan import cursor
#from msydwork.config.config_msydonline import cursor
from msydwork.prod.pro_config import cursor


today_date = datetime.strptime('20191002',('%Y%m%d'))   # 先将datetime.datetime转化为str,再转化为datetime.datetime

def select_data():
    sql_date = "select business_date from ms_system_date where process_status = 'S';"
    cursor.execute(sql_date)
    results_date = cursor.fetchall()
    date = results_date[0][0]
    #print(date)
    date_time = datetime.strptime(date.strftime('%Y%m%d'),('%Y%m%d'))    # 先将datetime.date转换为str,再转化为datetime.datetime
    #print(type(date),type(date_str),type(today_date))
    #print(date_time)
    return(date_time)


def ms_loan(out_process,process):
    sql_loan = 'select id,borrow_time,outside_process_no,process_no,curr_term,status from ms_loan where outside_process_no="%s" and process_no = "%s" and status <> "7";' %(out_process,process)
    cursor.execute(sql_loan)
    results_loan = cursor.fetchall()
    loan = results_loan[0]
    #print(loan)
    return (loan)



def ms_plan(loan_id):
    sql_loan = 'select loan_id,plan_id,term,plan_add_date from ms_plan where loan_id="%s" order by plan_id desc limit 1 ;' %(loan_id)
    cursor.execute(sql_loan)
    results_plan = cursor.fetchall()
    repay_plan = []
    for plans in results_plan:
        row = []
        for plan in plans:
            try :
                row.append(plan.strftime('%Y%m%d'))
            except:
                row.append(plan)
        repay_plan.append(row)
    #print(repay_plan)
    return(repay_plan)


def ms_repayment_plan(loan_id):
    sql_loan = 'select loan_id,id,repay_plan_no,curr_term,repay_status,loan_pmt_due_date,loan_init_prin,loan_term_prin,loan_term_int from ms_repayment_plan where loan_id="%s" ;' %(loan_id)
    cursor.execute(sql_loan)
    results_repayment = cursor.fetchall()
    repayment_plan = []
    for plans in results_repayment:
        row = []
        for plan in plans:
            try :
                row.append(datetime.strptime(plan.strftime('%Y%m%d'), ('%Y%m%d')))
            except:
                row.append(plan)
        repayment_plan.append(row)
    #print(repayment_plan)
    return(repayment_plan)


# 将要支付的期数
def prepay_term(loan_id):
    sql_loan = 'select curr_term from ms_repayment_plan where loan_id="%s" and repay_status = 0 order by id limit 1 ;' %(loan_id)
    cursor.execute(sql_loan)
    results_repayment = cursor.fetchall()
    pay_term = results_repayment[0][0]
    #print(pay_term)
    return(pay_term)


def normal_repay(repay,curr_term,days,process_no):
    for info in repay:
        orgPlanNo = info[2]
        seqNo = info[3]
        rpySts = info[4]
        rpyDay = info[5]
        serviceFee = info[8]
        try:
            day = int(str(days - rpyDay).split(' day')[0])
        except:
            day = 0              # 0:00:00
        # 宽限期3天
        if day<4:
            c_day = 0
        else:
            c_day = day
        rpyAmt = info[7]
        data = API_MSYD['preview_result']
        data['orgOrdNo'] = process_no
        data['orgPlanNo'] = orgPlanNo
        data['seqNo'] = seqNo
        data['rpySts'] = rpySts
        data['rpyDay'] = rpyDay.strftime('%Y%m%d')
        data['serviceFee'] = str(serviceFee)
        lateFee = Decimal('0.00')
        if rpySts == 0 and curr_term > seqNo:           # 当期未还、逾期
            data['rpyAmt'] = str(rpyAmt)
            lateFee = float_deal(rpyAmt * Decimal('0.001')) * c_day     # 四舍五入 * 天数
            data['lateFee'] = str(lateFee)
        else:                               # 当期未还、未逾期；当期已还
            data['rpyAmt'] = str(rpyAmt)
            data['lateFee'] = '0.00'
        repay_info = json.dumps(data, indent=4, ensure_ascii=False)
        print("应还总金额：",rpyAmt + lateFee + serviceFee)
        print(repay_info + ',')



'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
1.判断是否逾期：day  当前系统时间-到期还款时间
2.判断当期是否已还：（计划待支付期数）curr_term + 1 >= pay_term(实际待支付期数) 固定  seqNo<pay_term 是已还
3.当期未还未逾期，当期未还已逾期，当期已还
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
def advance_settle(repay,pay_term,curr_term,days,process_no,loan_status):
    data = API_MSYD['preview_result']
    data.pop('orgPlanNo')
    data['rpySts'] = 0
    rpyAmt = Decimal('0.00')
    serviceFee = Decimal('0.00')
    lateFee = Decimal('0.00')
    for info in repay:
        data['orgOrdNo'] = process_no
        seqNo = info[3]
        rpySts = info[4]
        rpyDay = info[5]
        try:
            day = int(str(days - rpyDay).split(' day')[0])
        except:
            day = 0              # 0:00:00
        # 宽限期3天
        if loan_status == 6:
            c_day = day
        else:
            c_day = 0
        repayAmt = info[7]
        if seqNo == pay_term:
            data['seqNo'] = pay_term
            data['rpyDay'] = rpyDay.strftime('%Y%m%d')

        # 未还期数，
        if rpySts == 0:
            if curr_term < seqNo:
                print('计划要还期数、未还，未逾期：',seqNo,curr_term ,day)
                rpyAmt = rpyAmt + repayAmt
                serviceFee = serviceFee + float_deal(repayAmt * Decimal('0.03'))

            elif curr_term == seqNo:
                print('计划要还期数、未还，未逾期：', seqNo, curr_term, day)
                rpyAmt = rpyAmt + repayAmt
                serviceFee = serviceFee + info[8]

            elif curr_term > seqNo:
                print('计划要还期数、未还，已逾期：', seqNo, curr_term, day)
                lateFee = lateFee + float_deal(repayAmt * Decimal('0.001')) * c_day
                rpyAmt = rpyAmt + repayAmt
                serviceFee = serviceFee + info[8]

    data['rpyAmt'] = str(rpyAmt)
    data['lateFee'] = str(lateFee)
    data['serviceFee'] = str(serviceFee)
    repay_info = json.dumps(data, indent=4, ensure_ascii=False)
    print('总还款金额：',rpyAmt+lateFee+serviceFee)
    print(repay_info)


def refund(repay,pay_term,curr_term,days,process_no,over_day):
    # 可以进行退货
    if over_day < 8:
        for info in repay:
            orgPlanNo = info[2]
            seqNo = info[3]
            rpySts = info[4]
            rpyDay = info[5]
            serviceFee = info[8]
            rpyAmt = info[7]
            data = API_MSYD['preview_result']
            data['orgOrdNo'] = process_no
            data['orgPlanNo'] = orgPlanNo
            data['seqNo'] = seqNo
            data['rpySts'] = rpySts
            data['rpyDay'] = rpyDay.strftime('%Y%m%d')
            data['serviceFee'] = str(serviceFee)
            data['rpyAmt'] = str(rpyAmt)
            data['lateFee'] = 0.00
            repay_info = json.dumps(data, indent=4, ensure_ascii=False)
            print(repay_info + ',')
    else:
        print('无法进行退货，走提前结清')
        advance_settle(repay, pay_term, curr_term, days, process_no,over_day)


def main(rpyMod):
    process_no = 'LW20200827HB000104'
    days = select_data()
    loan_info = ms_loan('50620200827165151614356809', process_no)
    loan_id = loan_info [0]
    loan_status = loan_info [5]
    borrow_time = datetime.strptime(loan_info [1].strftime('%Y%m%d'), ('%Y%m%d'))
    try:
        over_day = int(str(days - borrow_time).split(' day')[0])          # 借款成功天数
    except:
        over_day = 0                                    # 0:00:00
    if str(days)[0:7] != str(borrow_time)[0:7]:         # 如果不相等跨月，不能退货
        over_day = 8
    curr_term = loan_info[4] +1                         # 借据表记录当期
    pay_term = prepay_term(loan_id)
    repay = ms_repayment_plan(loan_id)
    if rpyMod == '1':       # 还某期
        normal_repay(repay,curr_term,days,process_no)
    if rpyMod == '2':       # 提前结清
        advance_settle(repay,pay_term,curr_term,days,process_no,loan_status)
    if rpyMod == '3':       # 退货
        refund(repay,pay_term,curr_term,days,process_no,over_day)


if __name__ == '__main__':
    #select_data()
    main('2')

